package com.zjb.demo.framework.manager;

import cn.hutool.http.useragent.UserAgentUtil;
import com.zjb.demo.common.constant.Constants;
import com.zjb.demo.common.domain.dto.SysLoginInfo;
import com.zjb.demo.common.util.AddressUtils;
import com.zjb.demo.system.service.SysLoginInfoService;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import org.noear.solon.scheduling.annotation.Async;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * 异步任务管理器
 *
 * @author 庄佳彬
 * @since 2023/12/25 20:56
 */
@Component
public class AsyncManager {

    public static final Logger log = LoggerFactory.getLogger(AsyncManager.class);
    @Inject
    private SysLoginInfoService loginInfoService;

    @Async
    public void saveLoginInfo(String userName, String status,String message) {
        var ctx = Context.current();
        var userAgent = UserAgentUtil.parse(ctx.header("User-Agent"));
        var ip = ctx.realIp();
        var address = AddressUtils.getRealAddressByIP(ip);
        var os = userAgent.getOs().getName();
        var browser = userAgent.getBrowser().getName();
        log.info("用户：{} 登录成功，IP：{}，地址：{}，系统：{}，浏览器：{}", userName, ip, address, os, browser);
        var loginInfo = new SysLoginInfo();
        loginInfo.setUserName(userName);
        loginInfo.setLoginLocation(address);
        loginInfo.setIpaddr(ip);
        loginInfo.setBrowser(browser);
        loginInfo.setOs(os);
        loginInfo.setMsg(message);
        if(Objects.equals(status, Constants.SUCCESS)){
            loginInfo.setStatus("0");
        }else if(Objects.equals(status, Constants.ERROR)){
            loginInfo.setStatus("1");
        }
        loginInfoService.save(loginInfo);
    }

}
